<?php 
	$_SESSION['realpage'] = true;
	
	require_once "./class.Message.php";
 	require_once "./class.User.php";
 	require_once "./class.GeneralServices.php";
 	session_start();
 	
// 	$_SESSION['userObj'] = GeneralServices::getService()->login("arg","arg");
 	
 	if(isset($_SESSION['userObj']))
 	{
 		$userObj = $_SESSION['userObj'];
 		$msgs = GeneralServices::getService()->getUserMessages($userObj->uid , 4, 0);
													 		//($uid,$limit,$downpour)
 	}
 	else 
 	{
 		require './hack.php';
 	}
 	
 	?>
 	
<html>
<head>
<?php require_once "./HtmlIncludes.php";?>
<title>Urban Dynamics</title>
</head>
<body onload="load();">
    <script type="text/javascript">
		function load()
		{
			var ur = window.parent.document.URL;			
			if(ur.substring(ur.length - 15, ur.length) != "Pages/panes.php")
				window.location.replace("./panes.php");
		}
    </script>
<script type="text/javascript">
var friendsId=0;

function SearchFriend(creteria, limit)
{
	if(creteria != null && creteria != '')
	{
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
		    {
			    if(xmlhttp.responseText == 'false')
			    {
					alert('false');
			    }
			    else
			    {
				    if(xmlhttp.responseText != "")
				    {
				    	$('#friendSearchResults').html(xmlhttp.responseText);
				    }else
				    {
				    	$('#friendSearchResults').html('None found');
				    }
			    }
			}
		};
		xmlhttp.open("GET","./ajax.php?method=searchFriendDivs&sid="+"<?php echo session_id(); ?>"+"&creteria="+creteria+"&limit="+limit,true);
		xmlhttp.send();
	}
}

function fenterPressed(e)
{
	if(e.keyCode == 13)
	{
		SearchFriend($('#friendsText').val(), 4);
	}
}
function setMsgTarget(fid,fname)
{
	friendsId = fid;
	$('#msgTarget').html(fname);
	return true;
}
</script>
<div id="dialog-form" title="Compose message">
    <div class="">
    <span><input id="friendsText" type="text" value="Search for a friend" onmouseover="RemoveText('friendsText', 'Search for a friend')" onmouseout="ReturnText('friendsText', 'Search for a friend')" onkeypress="fenterPressed(event)"/></span>
			    
    <div id="friendSearchResults"></div>
    </div>
    
	<div class="leftAlligned">To:&nbsp</div><div class="leftAlligned"  id="msgTarget" name="msgTarget"></div>
	<br><br>
	<form>
	<fieldset>
		<label class="leftAlligned smallMargin" for="content">Content</label>
		<br>
		<textarea cols="38" rows="5" name="content" id="content" class="text ui-widget-content ui-corner-all"></textarea>
	</fieldset>
	</form>
	<p class="validateTips"></p>
</div>


<script>
//downpour for new msgs, in msgs it's uppour since it's by descending order
downpour = <?php echo $msgs[count($msgs) - 1 ]->mid ; ?>;

function openNewMsgUI()
{
	openMsgDialog();
	return false;
}
function openMsgPage(userId)
{
	url = "./Thread.php?friendId=" +userId;						    	
	window.location.replace(url);
	return true;
}
function getMoreMsgs()
{
	if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
		    {
			    if(xmlhttp.responseText == '[]' || xmlhttp.responseText == '')
			    {
			    	$('#ThreadsMore').html('&nbsp;&nbsp;No more conversations found');			    
			   	}
			    else
			    {
			    	myuid = <?php echo $userObj->uid ;?>;
				    $tmp='';
				    objArr	 = jQuery.parseJSON(xmlhttp.responseText);
    			    for(i=0;i<objArr.length;i++)
    			    {
        			    obj = objArr[i];
        			    fid = (myuid == obj.sender)? obj.receiver : obj.sender;
        			    fname =  (myuid == obj.sender)? 'to '+ obj.receiverName : 'from '+obj.senderName;
        			   
    					 	
        			    jQuery(" <div />" )
        	             .addClass( "UserMessage" ) //.onclick('openMsgPage('+fid+')')
        	             .html( "<div class=\"leftAlligned\" onclick=\"openMsgPage("+fid+");\">"
                	             + "<span class=\"leftAlligned\">"+fname+":</span> <br>"
                	             +"<div class=\"msgContent leftAlligned\">"+shorten(obj.thread)+"</div>"
                	             +" </div>"
								 +"<div class=\"msgDate rightAlligned\">"+obj.lostTime+" ago </div>"
                	             +"<br/>"
            	         ).appendTo("#msgContainer");
        			   $("#msgContainer").append("<br>");
					  downpour = obj.mid; // set new downpour
    			    }
				
			    }
			}
		};
		xmlhttp.open("GET","./ajax.php?method=getMoreMessages&sid=<?php echo session_id(); ?>&limit=5&downpour="+downpour,true);
		xmlhttp.send();
	return false;
}

function refreshMsgs()
{
	if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
		    {
			    if(xmlhttp.responseText == '[]' || xmlhttp.responseText == '')
			    {
			    	$('#ThreadsMore').html('&nbsp;&nbsp;No conversations found');			    
			   	}
			    else
			    {
			    	$('#msgContainer').html('');
			    	myuid = <?php echo $userObj->uid ;?>;
				    $tmp='';
				    objArr	 = jQuery.parseJSON(xmlhttp.responseText);
    			    for(i=0;i<objArr.length;i++)
    			    {
        			    obj = objArr[i];
        			    fid = (myuid == obj.sender)? obj.receiver : obj.sender;
        			    fname =  (myuid == obj.sender)? 'to '+ obj.receiverName : 'from '+obj.senderName;
        			   
    					 	
        			    jQuery(" <div />" )
        	             .addClass( "UserMessage" ) 
        	             .html( "<div class=\"leftAlligned\" onclick=\"openMsgPage("+fid+");\">"
                	             + "<span class=\"leftAlligned\">"+fname+":</span> <br>"
                	             +"<div class=\"msgContent leftAlligned\">"+shorten(obj.thread)+"</div>"
                	             +" </div>"
								 +"<div class=\"msgDate rightAlligned\">"+obj.lostTime+" ago </div>"
                	             +"<br/>"
            	         ).appendTo("#msgContainer");
        			   $("#msgContainer").append("<br>");
					  downpour = obj.mid; // set new downpour
    			    }
				
			    }
			}
		};
		lmt=$(".UserMessage").length;
		xmlhttp.open("GET","./ajax.php?method=getMoreMessages&sid=<?php echo session_id(); ?>&limit="+lmt+"&downpour=0",true);
		xmlhttp.send();
	return false;
}

</script>
    	<div class="PaneHeader">
    		<div class="leftAlligned">Inbox</div>
    		<div class="rightAlligned  buttons">
    		
			    <div class="rightAlligned"  id='dialogBtn'> Compose </div>
				<div class="rightAlligned"  id='refreshBtn' > refresh </div>
		
			</div>
    	</div>    	
    	<br>
		<?php
		$numOfMsgs= count($msgs); // is saved because we need it again in get older msgs button
		if ($numOfMsgs == 0)
		{
		?>
		<div>
			No messages found! <br> would you like to start sending msgs to other users? <br> click on <span onclick="openNewMsgUI()"> New Message </span>
		</div>
		<?php } else {?>
		<div class = "msgCont" id="msgContainer" name="msgContainer">
			<?php 
			foreach ($msgs as $msg)
			{
			?>
				<div class="UserMessage" style="cursor: pointer;" onclick='openMsgPage(<?php echo ($userObj->uid == $msg->sender)? $msg->receiver : $msg->sender; ?>)'>
					<div class="leftAlligned">
					 <span class="leftAlligned"> <?php 
					 if($userObj->uid == $msg->sender)
					 	echo 'to '.$msg->receiverName;
					 else  
					 	echo 'from '.$msg->senderName;
					 ?>:</span> <br>
					 <div class="msgContent leftAlligned"><?php echo $msg->thread; ?></div>
					</div>
					<div class="msgDate rightAlligned"><?php echo $msg->timePassed().' ago'; ?></div>
				</div>
			<br> 
			<?php } // end of loop
			?>			
		</div>
		<?php // end of else 
		}
		if ($numOfMsgs >=1) //return to 10
		{
		?>
		<br>
		<div id="ThreadsMore" class="moreNote"></div>
		<br>
		<div class="GetMoreMsgsButton rightAlligned" onclick="getMoreMsgs();">
			older messages
		</div>
		<?php 
		} // end of more msgs button
		?>
    </body>
  
	<script type="text/javascript">
	var tmpObj;
	function openMsgDialog() {
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		var content = $( "#content" ),
			allFields = $( [] ).add( content ),
			tips = $( ".validateTips" );
	
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}
	
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}
	
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			height: 340,
			width: 400,
			modal: true,
			buttons: {
				"Send a new message": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );
	
					bValid = bValid && checkLength( content, "content", 3, 3000 );
					tmpObj=this;
					if ( bValid ) {
						//do ajax
						if (window.XMLHttpRequest)
						  {// code for IE7+, Firefox, Chrome, Opera, Safari
						  xmlhttp=new XMLHttpRequest();
						  }
						else
						  {// code for IE6, IE5
						  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
						  }
						xmlhttp.onreadystatechange=function()
						  {
						  if (xmlhttp.readyState==4 && xmlhttp.status==200)
						    {
							    if(xmlhttp.responseText == 'false')
							    {
							    	alert('error!');		    	
							    }
							    else
							    {
							    	url = "./Thread.php?friendId=" +friendsId;						    	
							    	setMsgTarget(null,"");
							    	$( tmpObj ).dialog( "close" );						    	
							    	window.location.replace(url);
							    }
							}
						  };
						xmlhttp.open("GET","./ajax.php?method=sendMsg&friendid="+friendsId+"&content="+replaceBR($("#content").val())+"&sid="+"<?php echo session_id(); ?>",true);
						xmlhttp.send();
						//end of ajax
					}
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		
		$( "#dialogBtn" )
			.button()
			.click(function() {
				$( "#dialog-form" ).dialog( "open" );
			});
		
		$( "#refreshBtn" )
			.button()
			.click(function() {
				refreshMsgs();
			});
	
	}
	openMsgDialog();
	</script>
</html>
<?php 
	$_SESSION['realpage'] = false;
?>